package com.sans.common.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestToken {

	private static final Base64.Encoder ENCODER = Base64.getEncoder();

	private static final Base64.Decoder DECODER = Base64.getDecoder();
	static ThreadLocal<Object> threadLocal = new ThreadLocal<>();
	public static void main(String[] args) throws Exception {
		try {

			//1095769771246354432

			Map<String, String> map = new TreeMap<String, String>();
			/*map.put("eip_serv_id", "app.getMessageListTest");
			map.put("codeId","11");
			map.put("lng","117.13662");
			map.put("lat","31.844191");*/

			/*map.put("eip_serv_id", "app.getPlusVipRights");
			map.put("QQ","");
			map.put("resName","网上国网50元电费优惠券");
			map.put("rightsType","01");
			map.put("retId","1687345327942");
			map.put("couponsNum","1");
			map.put("resId","RJ0006058");
			map.put("prodPrcinsId","60006777059038");*/

			/*map.put("eip_serv_id", "app.timeAreaFlowOrder");
			map.put("orderType","1");
			map.put("latitude","117.241687");
			map.put("longitude","31.850387");
			map.put("prodPrcId","PIBP82312");
			map.put("prodId","BP82310");
			map.put("prodPrcName","分时分区流量五天日间包（20元40GB）");
			map.put("discountType","1");
			map.put("msgId","4444");
			map.put("charge","2000");
			map.put("spayCharge","2000");*/

			map.put("eip_serv_id", "app.againConfirmPopup");
			map.put("businessType","timeAreaFlow");
			map.put("pageName","PIBP82311");







			//map.put("clientVersion","7.2.8");
			/*map.put("ztVersion","7.3.0");
			map.put("deviceId","1111");*/
			//map.put("sideType","1");
			/*map.put("prodPrcId", "11111");
			map.put("prodPrcId_12580", "934080699435065344");
			map.put("prodName", "淮小南牛肉汤满20减10元代金券");*/
			//map.put("uid","LRFlPpYweVFCGZnPlkIvTIFAYVWKR28Mt%2BhOrIKEX6hOTz41dE74EMqAeNXtPDYlqllBeObGM2hHTtSYjiVu35A1aLEsucNk9FW323kwDouufFV%2Fd7YKiOvwN3D5n31Bxo1w6m%2FQMyezUL6%2FZK8h1GH5OjnszoqNwnRhVSKB9e4kI%");
			/*map.put("eip_serv_id", "app.hcyTaskActivitySaveFile");
			map.put("awardName","1GB国内流量");
			map.put("deviceId","e48076e3342467bd");
			map.put("sideType","1");
			map.put("ucode","");*/
			/*map.put("ytnb","true");
			map.put("phoneNo","tnoHFNxxpsJq4C/jCqOgWw==");
			map.put("type","1");
			map.put("isChange","");*/

			/*map.put("isMyMobile","0");
			map.put("freshFlag","0");
			map.put("clientType","ios");
			map.put("clientVersion","7.2.8");*/
			/*map.put("eip_serv_id", "app.getPlusVipRights");
			map.put("rightsType","02");
			map.put("retId", "1657097120439");
			map.put("resId", "R00005839");
			map.put("resName", "唯品会40元券包");
			map.put("prodPrcinsId", "60006132943618");
			map.put("couponsNum", "");*/
			Set<String> keys = map.keySet();
			StringBuilder sb = new StringBuilder();
			for(String key : keys){
				sb.append(key).append("=").append(map.get(key)).append("&");
			}
			String param = sb.substring(0, sb.length() - 1);
			System.out.println(param+"&token="+getMD5String(param, "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getMD5String(String plainText, String charset)throws UnsupportedEncodingException {
		plainText+="&key=SD7B3L3P";
		StringBuffer buf = new StringBuffer("");
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes(charset));
			byte b[] = md.digest();
			int i;
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return buf.toString();
	}


	public static MultipartFile base64Convert(String base64) {
		String[] baseStrs = base64.split(","); //base64编码后的图片有头信息所以要分离出来   [0]data:image/png;base64, 图片内容为索引[1]
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] b = new byte[0];
		try {
			b = decoder.decodeBuffer(baseStrs[1]); //取索引为1的元素进行处理
		} catch (IOException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < b.length; ++i) {
			if (b[i] < 0) {
				b[i] += 256;
			}
		}
		return new Base64DecodeMultipartFile(b, baseStrs[0]);//处理过后的数据通过Base64DecodeMultipartFile转换为MultipartFile对象
	}
	public static class Base64DecodeMultipartFile implements MultipartFile {
		private final byte[] imgContent;
		private final String header;

		public Base64DecodeMultipartFile(byte[] imgContent, String header) {
			this.imgContent = imgContent;
			this.header = header.split(";")[0];
		}

		@Override
		public String getName() {
			return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
		}

		@Override
		public String getOriginalFilename() {
			return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
		}

		@Override
		public String getContentType() {
			return header.split(":")[1];
		}

		@Override
		public boolean isEmpty() {
			return imgContent == null || imgContent.length == 0;
		}

		@Override
		public long getSize() {
			return imgContent.length;
		}

		@Override
		public byte[] getBytes() throws IOException {
			return imgContent;
		}

		@Override
		public InputStream getInputStream() throws IOException {
			return new ByteArrayInputStream(imgContent);
		}

		@Override
		public void transferTo(File dest) throws IOException, IllegalStateException {

			new FileOutputStream(dest).write(imgContent);

		}
	}


	public static Long getmicTime(){
		Long cutTime = System.currentTimeMillis() * 1000;
		Long nanoTime = System.nanoTime();
		return cutTime + (nanoTime - nanoTime / 1000000 * 1000000) / 1000;
	}

	private static String getSize(double size) {
		int i = 0;
		String[] units = new String[]{"bps", "Kbps", "Mbps", "Gbps"};
		double sized = (double) size;
		while (sized >= 1024 && i < 3) {
			sized = sized / 1024;
			i++;
		}
		return String.format("%.2f%s", sized, units[i]);
	}



}